package top.hmtools.annotation;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import top.hmtools.model.ControllerInfoModel;
import top.hmtools.model.ParamInfoModel;
import top.hmtools.model.ResultInfoModel;

/**
 * 解析ControllerInfo注解信息为实体类对象的工具
 * @author HyboJ
 *
 */
public class ControllerInfoTools {
	
	/**
	 * 将指定对象中的ControllerInfo注解解析成ControllerInfoModel
	 * @param clazz
	 * @return
	 */
	public static ControllerInfoModel getControllerInfoOfClass(Class<?> clazz){
		ControllerInfo controllerInfoAnno = clazz.getAnnotation(ControllerInfo.class);
		ControllerInfoModel result = controllerInfoAnno2Model(controllerInfoAnno);
		return result;
	}
	
	/**
	 * 将指定方法中ControllerInfo注解解析成ControllerInfoModel
	 * @param method
	 * @return
	 */
	public static ControllerInfoModel getControllerInfoOfMethod(Method method){
		ControllerInfo controllerInfoAnno = method.getAnnotation(ControllerInfo.class);
		ControllerInfoModel result = controllerInfoAnno2Model(controllerInfoAnno);
		return result;
	}
	
	/**
	 * 将ControllerInfo注解 信息解析成 ControllerInfoModel
	 * @param controllerInfo
	 * @return
	 */
	private static ControllerInfoModel controllerInfoAnno2Model(ControllerInfo controllerInfo ){
		ControllerInfoModel result = null;
		if(null != controllerInfo){
			result = new ControllerInfoModel();
			
			result.setInputDataFormat(controllerInfo.inputDataFormat());
			result.setName(controllerInfo.name());
			result.setOutputDataFormat(controllerInfo.outputDataFormat());
			
			ParamInfo[] paramInfos = controllerInfo.paramInfos();
			List<ParamInfoModel> paramInfoList = new ArrayList<ParamInfoModel>();
			for(ParamInfo tmp:paramInfos){
				ParamInfoModel model = new ParamInfoModel();
				model.setComment(tmp.comment());
				model.setDataMaxLength(String.valueOf(tmp.maxLength()));
				model.setDataMinLength(String.valueOf(tmp.minLength()));
				model.setDataType(tmp.dataType().toString());
				model.setName(tmp.paramName());
				
				model.setDefaultValue(tmp.defaultValue());
				model.setRequired(tmp.isRequired());
				
				paramInfoList.add(model);
			}
			result.setParamInfoModels(paramInfoList);
			
			ResultInfo[] resultInfos = controllerInfo.ResultInfos();
			List<ResultInfoModel> resultInfoModels = new ArrayList<ResultInfoModel>();
			for(ResultInfo tmp:resultInfos){
				ResultInfoModel model = new ResultInfoModel();
				model.setComment(tmp.comment());
				model.setDataMaxLength(String.valueOf(tmp.maxLength()));
				model.setDataMinLength(String.valueOf(tmp.minLength()));
				model.setDataType(String.valueOf(tmp.dataType()));
				model.setName(tmp.resultName());
				
				model.setDefaultValue(tmp.defaultValue());
				model.setRequired(tmp.isRequired());
				
				resultInfoModels.add(model);
			}
			result.setResultInfoModels(resultInfoModels);
			
			result.setUsedFor(controllerInfo.usedFor());
		}
		return result;
	}

}
